/**
 * @description  个券偏离度监测
 * @author
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { SecondHeaderC, TableC, ModalC, InputC } from '../../../comps';
import Style from './style.less';
import ketou from '../../../assets/busi/reportingServices/tick_icon.png';
import buketou from '../../../assets/busi/reportingServices/cross_icon.png';
import columnsDict from './columnsDict';
import { AdvancedSearch, DATA_ENTRY } from '../../../components';
import moment from 'moment';
import { message } from 'antd';

export const FormItemLayout = {
  labelCol: {
    lg: { span: 6, offset: 0 },
    xl: { span: 6, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    lg: { span: 16, offset: 0 },
    xl: { span: 16, offset: 0 },
    xxl: { span: 16, offset: 0 },
  },
};
const infoObj = { 1: '正偏离度绝对值超过0.5%', 2: '负偏离度绝对值超过0.25%', 3: '负偏离度绝对值连续两个交易日超过0.5%' };
@Form.create()
class DeviationHandle extends PureComponent {
  constructor() {
    super();
    this.state = {
      visible: false, // 是否可见
      detail: undefined, // 每行数据
      viewVisible: false, // 查看说明
      detailView: undefined, // 查看说明 每行数据
      descList: [], // 说明列表
      pageSize: 20, // 每页条数
      currentPage: 1, // 当前页码
      total: 0, // 总条数
    };
  }

  // 获取columns
  getColumns = (title) => {
    let columns = [];
    columnsDict.map((item) => {
      if (item.title == title) {
        columns = item.columns;
      }
    });
    return columns;
  };

  // 关闭弹窗
  onCancel = () => {
    this.setState({
      visible: false,
      detail: undefined,
    });
  };

  // 点击确定按钮保存说明
  onOk = (e) => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const { detail } = this.state;
    const editDescription = getFieldsValue().editDescription || '';
    this.props.dispatch({
      type: 'cashManagementReportM/saveDescription',
      payload: {
        id: detail?.id,
        editDescription,
      },
      callback: () => {
        // 成功则关闭模态框
        this.onCancel();
        // 通知父组件刷新表格
        this.props?.getDeviationControl();
      },
    });
  };

  // 查询编辑说明数据
  handleQueryData = (e) => {
    const { detailView } = this.state;
    if (e && e?.startDate && e?.endDate) {
      if (e.startDate.format('YYYYMMDD') > e.endDate.format('YYYYMMDD')) {
        message.warning('开始日期不能大于结束日期');
        return;
      }
    }
    const obj = {};
    if (e) {
      if (e.startDate) obj.startDate = e.startDate.format('YYYY-MM-DD');
      if (e.endDate) obj.endDate = e.endDate.format('YYYY-MM-DD');
    }
    this.props.dispatch({
      type: 'cashManagementReportM/quereyEditInfo',
      payload: {
        productcode: detailView?.productcode,
        tradingcode: detailView?.tradingcode,
        exchangecode: detailView?.exchangecode,
        ...obj,
      },
      callback: (data) => {
        this.setState({
          descList: data || [],
          total: data?.length || 0,
        });
      },
    });
  };

  // 展示编辑说明弹窗
  showModal = () => {
    const { visible, detail } = this.state;
    return (
      <ModalC
        title={'编辑说明'}
        visible={visible}
        width={600}
        height={135}
        maskClosable={false}
        onOk={this.onOk}
        onCancel={this.onCancel}
        confirmLoading={this.props.loading}
        wrapClassName={Style.myModal}
      >
        <div>
          <InputC
            dataIndex='editDescription'
            title={''}
            showTextArea={true}
            form={this.props.form}
            style={{ height: '150px' }}
            initialValue={detail?.editDescription}
            placeholder='请输入说明'
          />
        </div>
      </ModalC>
    );
  };

  // 表格页码变更
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      pageSize,
    });
  };

  // 展示查看说明弹窗
  showView = () => {
    const { viewVisible, detailView, descList } = this.state;
    const columns = [
      {
        key: 'importdate',
        title: '日期',
        type: 'date',
      },
      {
        key: 'editDescription',
        title: '说明内容',
        align: 'left',
      },
    ];
    return (
      <ModalC
        title={`${detailView.tradingcode}-${detailView.secuabbr}-偏离度说明`}
        visible={viewVisible}
        width={1200}
        height={400}
        maskClosable={false}
        onOk={() => {
          this.setState({ viewVisible: false });
        }}
        onCancel={() => {
          this.setState({ viewVisible: false });
        }}
      >
        <div className={Style.searchCls}>
          <AdvancedSearch
            dataSource={[
              {
                dataIndex: ['startDate', 'endDate'],
                title: '日期区间',
                type: DATA_ENTRY.RANGEDATE,
                allowClear: true,
                formItemLayout: FormItemLayout,
              },
            ]}
            allowClear={false}
            fieldInRow={1}
            onQuery={this.handleQueryData}
          />
        </div>
        <TableC
          columns={columns}
          dataSource={descList}
          scroll={{ x: 'max-content' }}
          rowKey='key'
          onChange={this.handleTableChange}
          current={this.state.currentPage}
          pageSize={this.state.pageSize}
          total={this.state.total}
          loading={this.props.loadingList}
        />
      </ModalC>
    );
  };

  render() {
    const { data, loading } = this.props;
    const { visible, viewVisible } = this.state;
    const iconInfo = {
      0: {
        className: 'prohibit',
        img: buketou,
        name: '禁止',
      },
      1: {
        className: 'adopt',
        img: ketou,
        name: '通过',
      },
    };

    return (
      <>
        {data &&
          data.map((r, index) => {
            return (
              <div key={index}>
                {r?.title && (
                  <div name={'xjgl-pdf'} style={{ marginBottom: '16px' }}>
                    <SecondHeaderC
                      title={r.title}
                      Left={
                        <div className={Style[iconInfo[r.state]?.className]} style={{ marginLeft: '20px' }}>
                          {' '}
                          <img src={iconInfo[r.state]?.img} /> {iconInfo[r.state]?.name}
                        </div>
                      }
                      bottomHeight={false}
                    />
                  </div>
                )}
                {(r?.dataSource?.length != 0 || loading) && (
                  <div name={'xjgl-pdf'} style={{ marginBottom: '16px' }}>
                    <TableC
                      columns={this.getColumns(r.title)
                        ?.map((x) => {
                          if (x.key == 'PLDinfoId') {
                            x.render = (text, record) => {
                              if (text == null || text == undefined || text == '') return '--';
                              const temp = text.split(',');
                              return (
                                <div>
                                  {temp?.map((item, key) => {
                                    return (
                                      <div key={key} className={item == 3 ? `${Style.red}  ${Style.infoDiv}` : Style.infoDiv}>
                                        {infoObj[item]}
                                      </div>
                                    );
                                  })}
                                </div>
                              );
                            };
                            return {
                              ...x,
                            };
                          }
                          if (x.key == 'PLD' || x.key == 'prePLD') {
                            x.type = 'rate';
                            return {
                              ...x,
                            };
                          }
                          if (x.key == 'valuationMarketValue' || x.key == 'thirdPartyValuation') {
                            x.type = 'number';
                            x.toFixed = 2;
                            return {
                              ...x,
                            };
                          }
                          return x;
                        })
                        ?.concat([
                          {
                            title: '操作',
                            key: 'operate',
                            type: 'operate',
                            width: 150,
                            operates: [
                              {
                                title: '编辑说明',
                                onClick: (record) => this.setState({ visible: true, detail: record }),
                              },
                              {
                                title: '查看说明',
                                onClick: (record) =>
                                  this.setState({ viewVisible: true, detailView: record }, () => {
                                    this.handleQueryData();
                                  }),
                              },
                            ],
                          },
                        ])}
                      dataSource={r?.dataSource || []}
                      hidePage={true}
                      rowKey='id'
                      selfScrollY={true}
                      loading={loading}
                      defaultExpandAllRows={true}
                      rowClassName={(record) => {
                        const cls = record.editDescription ? '' : Style.noExpend;
                        return record.isRealHold === '0' ? `${Style.redCls} ${cls}` : `${cls} table-row`;
                      }}
                      expandedRowKeys={this.state.expandedRowKeys ? this.state.expandedRowKeys : r?.dataSource?.map((item) => item.id)}
                      onExpandedRowsChange={(expandedRows) => {
                        // 默认展开总是有一个不展开,所以这里首次加载的时候单独赋值
                        this.setState({ expandedRowKeys: this.state.expandedRowKeys ? [...expandedRows] : r?.dataSource?.map((item) => item.id) });
                      }}
                      expandedRowRender={(record) => <p style={{ margin: 0 }}>{record.editDescription}</p>}
                    />
                  </div>
                )}
              </div>
            );
          })}
        {visible ? this.showModal() : null}
        {viewVisible ? this.showView() : false}
      </>
    );
  }
}
export default connect(({ cashManagementReportM, loading }) => ({
  cashManagementReportM,
  loading: loading.effects['cashManagementReportM/saveDescription'],
  loadingList: loading.effects['cashManagementReportM/quereyEditInfo'],
}))(DeviationHandle);
